package com.have.blog.admin.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.have.blog.admin.constant.AdminBlogConstant;
import com.have.blog.admin.constant.AdminMessageConstant;
import com.have.blog.admin.domain.dto.SystemDictDataDto;
import com.have.blog.admin.domain.dto.SystemDictTypeDto;
import com.have.blog.admin.redis.AdminSysDictDataCacheService;
import com.have.blog.admin.service.SystemDictDataService;
import com.have.blog.admin.service.SystemDictTypeService;
import com.have.blog.admin.utils.SecurityUtil;
import com.have.blog.base.enums.BlogPublishStatus;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.wrapper.CommonPage;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.config.hloder.RequestHolder;
import com.have.blog.model.mapper.SysDictDataMapper;
import com.have.blog.model.mapper.SysDictTypeMapper;
import com.have.blog.model.models.SysDictData;
import com.have.blog.model.models.SysDictDataExample;
import com.have.blog.model.models.SysDictType;
import com.have.blog.model.models.SysDictTypeExample;
import com.have.blog.utils.MyBeanUtils;
import com.have.blog.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings("all")
public class SystemDictDataServiceImpl implements SystemDictDataService {
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private SysDictTypeMapper dictTypeMapper;
    @Autowired
    private SystemDictTypeService systemDictTypeService;
    @Autowired
    private AdminSysDictDataCacheService dictDataCacheService;

    @Override
    public Map<String, Object> getListByDictType(String dictType) {
        Map<String, Object> resultMap;

        resultMap = dictDataCacheService.getDictData(dictType);
        if (!CollectionUtils.isEmpty(resultMap)) {
            return resultMap;
        }
        SysDictTypeExample typeExample = new SysDictTypeExample();
        typeExample.createCriteria()
                .andDictTypeEqualTo(dictType)
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andIsPublishEqualTo(BlogPublishStatus.PUBLISH.getStatus());
        List<SysDictType> SysDictTypes = dictTypeMapper.selectByExample(typeExample);
        if (CollectionUtils.isEmpty(SysDictTypes)) {
            return null;
        }
        SysDictType sysDictTyp = SysDictTypes.get(0);
        SysDictDataExample dataExample = new SysDictDataExample();
        dataExample.createCriteria()
                .andIsPublishEqualTo(BlogPublishStatus.PUBLISH.getStatus())
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andDictTypeUidEqualTo(sysDictTyp.getUid());
        dataExample.setOrderByClause("create_time desc");
        List<SysDictData> dictDataList = dictDataMapper.selectByExample(dataExample);

        String defaultValue = null;
        for (SysDictData dictData : dictDataList) {
            if (dictData.getIsDefault() == AdminBlogConstant.ONE) {
                defaultValue = dictData.getDictValue();
                break;
            }
        }
        resultMap = new HashMap<>();
        resultMap.put(AdminBlogConstant.DEFAULT_VALUE, defaultValue);
        resultMap.put(AdminBlogConstant.LIST, dictDataList);
        System.out.println(resultMap);
        dictDataCacheService.saveDictData(resultMap, dictType, 1, TimeUnit.DAYS);
        return resultMap;
    }

    @Override
    public Map<String, Map<String, Object>> getDataListByDictTypeList(List<String> dictTypeList) {

        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        List<String> tempTypeList = new ArrayList<>();
        dictTypeList.forEach(item -> {
            Map<String, Object> tempMap = dictDataCacheService.getDataListByDictType(item);
            if (!CollectionUtils.isEmpty(tempMap)) {
                resultMap.put(item, tempMap);
            } else {
                tempTypeList.add(item);
            }
        });

        if (CollectionUtils.isEmpty(tempTypeList)) {
            return resultMap;
        }
        SysDictTypeExample typeExample = new SysDictTypeExample();
        typeExample.createCriteria()
                .andDictTypeIn(tempTypeList)
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andIsPublishEqualTo(BlogPublishStatus.PUBLISH.getStatus());
        List<SysDictType> sysDictTypeList = dictTypeMapper.selectByExample(typeExample);
        sysDictTypeList.forEach(item -> {
            SysDictDataExample dataExample = new SysDictDataExample();
            dataExample.createCriteria()
                    .andIsPublishEqualTo(BlogPublishStatus.PUBLISH.getStatus())
                    .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                    .andDictTypeUidEqualTo(item.getUid());
            dataExample.setOrderByClause("sort,create_time desc");
            List<SysDictData> list = dictDataMapper.selectByExample(dataExample);
            String defaultValue = null;
            for (SysDictData sysDictData : list) {
                if (sysDictData.getIsDefault() == AdminBlogConstant.ONE) {
                    defaultValue = sysDictData.getDictValue();
                    break;
                }
            }
            Map<String, Object> map = new HashMap<>();
            map.put(AdminBlogConstant.DEFAULT_VALUE, defaultValue);
            map.put(AdminBlogConstant.LIST, list);
            resultMap.put(item.getDictType(), map);
            dictDataCacheService.saveDataListByDictType(map, item.getDictType(), 1, TimeUnit.DAYS);
        });
        return resultMap;
    }

    @Override
    public Wrapper<CommonPage<SystemDictDataDto>> getList(SystemDictDataDto systemDictDataDto) {
        Page page = PageHelper.startPage(systemDictDataDto.getPageNum(), systemDictDataDto.getPageSize());
        SysDictDataExample example = new SysDictDataExample();
        SysDictDataExample.Criteria criteria = example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        if (StringUtils.isNotEmpty(systemDictDataDto.getKeyword()) && StringUtils.isNotEmpty(systemDictDataDto.getKeyword().trim())) {
            criteria.andDictLabelLike("%" + systemDictDataDto.getKeyword() + "%");
        }
        example.setOrderByClause("sort desc");
        List<SysDictData> sysDictData = dictDataMapper.selectByExample(example);
        List<SystemDictDataDto> systemDictDataDtos = MyBeanUtils.copyListProperties(sysDictData, SystemDictDataDto::new);
        CommonPage<SystemDictDataDto> systemDictDataDtoCommonPage = CommonPage.restPage(systemDictDataDtos);
        systemDictDataDtoCommonPage.setPageNum(page.getPageNum());
        systemDictDataDtoCommonPage.setPageSize(page.getPageSize());
        systemDictDataDtoCommonPage.setTotal(page.getTotal());
        List<SystemDictTypeDto> dictTypeDtoList = systemDictTypeService.getAll();
        Map<Integer, String> map = new HashMap<>();
        for (SystemDictTypeDto systemDictTypeDto : dictTypeDtoList) {
            map.put(systemDictTypeDto.getUid(), systemDictTypeDto.getDictType());
        }
        for (SystemDictDataDto dictDataDto : systemDictDataDtos) {
            dictDataDto.setDictType(map.get(dictDataDto.getDictTypeUid()));
        }
        return Wrapper.success(systemDictDataDtoCommonPage);
    }

    @Override
    public Wrapper add(SystemDictDataDto systemDictDataDto) {
        SysDictDataExample example = new SysDictDataExample();
        Integer adminUid = SecurityUtil.getUserId();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andDictLabelEqualTo(systemDictDataDto.getDictLabel());
        long count = dictDataMapper.countByExample(example);
        if (count > 0) {
            return Wrapper.failed(AdminMessageConstant.ENTITY_EXIST);
        }
        SysDictData sysDictData = MyBeanUtils.copyProperties(systemDictDataDto, SysDictData::new);
        sysDictData.setStatus(BlogStatus.ENABLE.getStatus());
        sysDictData.setCreatedAdminUid(adminUid);
        sysDictData.setUpdatedAdminUid(adminUid);
        sysDictData.setIsPublish(BlogPublishStatus.PUBLISH.getStatus());
        int result = dictDataMapper.insert(sysDictData);
        if (result > 0) {
            return Wrapper.success();
        }
        return Wrapper.failed("由于不可抗拒力，添加失败");
    }

    @Override
    public Wrapper delete(List<Integer> uids) {
        SysDictDataExample example = new SysDictDataExample();
        example.createCriteria()
                .andUidIn(uids);
        SysDictData template = new SysDictData();
        template.setStatus(BlogStatus.DISABLE.getStatus());
        int result = dictDataMapper.updateByExampleSelective(template, example);
        if (result > 0) {
            return Wrapper.success();
        }
        return Wrapper.failed("由于不可抗拒力，删除失败");
    }

    @Override
    public Wrapper edit(SystemDictDataDto systemDictDataDto) {
        SysDictData sysDictData = dictDataMapper.selectByPrimaryKey(systemDictDataDto.getUid());
        if (sysDictData == null) {
            return Wrapper.illegal();
        }
        Integer adminUid = RequestHolder.getAdminUid();
        BeanUtils.copyProperties(systemDictDataDto, sysDictData);
        sysDictData.setUpdatedAdminUid(adminUid);
        int result = dictDataMapper.updateByPrimaryKeySelective(sysDictData);
        if (result > 0) {
            return Wrapper.success();
        }
        return Wrapper.failed("由于不可抗拒力，编辑失败");
    }
}
